package cn.thrjit.service.impl;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.thrjit.feign.AppLoginFeignClient;
import cn.thrjit.mapper.DriverAuthMaterialMapper;
import cn.thrjit.mapper.DriverMapper;
import cn.thrjit.pojo.domain.*;
import cn.thrjit.pojo.param.RegisterSaveLoginParam;
import cn.thrjit.pojo.properties.DriverSettingProperties;
import cn.thrjit.rocketmq.Constants;
import cn.thrjit.rocketmq.GlobalExceptionCode;
import cn.thrjit.service.*;
import cn.thrjit.template.AppWeChatTemplate;
import cn.thrjit.utils.AssertUtil;
import cn.thrjit.utils.NameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



/**
 * <p>
 * 司机对象 服务实现类
 * </p>
 *
 * @author xxx
 * @since 2024-07-27
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IDriverService {
    @Autowired
    private IDriverWalletService walletService;
    @Autowired
    private IDriverSummaryService summaryService;
    @Autowired
    private IDriverSettingService settingService;
    @Autowired
    private DriverSettingProperties driverSettingProperties;
    @Autowired
    private AppWeChatTemplate appWeChatTemplate;
    @Autowired
    private AppLoginFeignClient appLoginFeignClient;
    @Autowired
    private DriverAuthMaterialMapper driverAuthMaterialMapper;

    @Override
    @Transactional
    public void register(String openid, String phoneCode) {
        // 获取openId，校验用户是否已注册
        String openId = appWeChatTemplate.getOpenIdByCode(openid);

        Driver driver = super.getOne(new QueryWrapper<Driver>().eq("open_id", openid));

        AssertUtil.isNull(driver,GlobalExceptionCode.PARAM_PHONE_EXIST);
        // String phone =appWeChatTemplate.getPhoneByAccess(phoneCode); 个人开发者因前端无法获取code所有无法使用该方法
        driver = new Driver();
        // 保存这个driver对象和openid到数据库的方法
        saveDriver(driver,openId,phoneCode);
        // 获取到保存的driver的id
        Long id = driver.getId();
        String password = "123456";
        // 使用satoken的BCrypt加密方式
        String hashpw = BCrypt.hashpw(password, BCrypt.gensalt());
        // 初始化从表把id传进去
        initDriverAssociation(id,hashpw);
        // 保存到feign接口
        saveLogin(id,openId, phoneCode, hashpw, Constants.Login.TYPE_DRIVER);
    }
    // 司机审核是否通过
    @Override
    public DriverAuthMaterial getRealAuthInfo() {
        long driverId = StpUtil.getLoginIdAsLong(); // 当前登录司机的id
        DriverAuthMaterial authMaterial = driverAuthMaterialMapper.selectOne(new LambdaQueryWrapper<DriverAuthMaterial>()
                .eq(DriverAuthMaterial::getDriverId,driverId)// 数据库的Driver要和loginIdAsLong相等
                .orderByDesc(DriverAuthMaterial::getRealAuthStatus)// 查询审核状态按desc排序
                .last("limit 1"));// 取最新一条数据
        return authMaterial; // 返回审核信息，做前端回显数据
    }
    // 保存司机审核信息
    private void saveLogin(Long id, String openId, String phoneCode, String password, Integer type) {

        RegisterSaveLoginParam registerSaveLoginParam =new RegisterSaveLoginParam();
        registerSaveLoginParam.setUsername(phoneCode);
        registerSaveLoginParam.setPassword(password);
        registerSaveLoginParam.setType(type);
        registerSaveLoginParam.setEnabled(false);
        registerSaveLoginParam.setAvatar(Constants.DEFAULT_AVATAR);
        registerSaveLoginParam.setAdmin(false);
        String name = NameUtil.getName();
        registerSaveLoginParam.setNickName(name);
        registerSaveLoginParam.setOpenId(openId);
        registerSaveLoginParam.setName(name);
        registerSaveLoginParam.setPhone(phoneCode);
        registerSaveLoginParam.setId(id);
        appLoginFeignClient.save(registerSaveLoginParam);
    }

    // 初始化司机关联表，因为这几张表是主键连接，只需要通过id(注释的已设默认值)
    private void initDriverAssociation(Long id,String hashpw){
        // 从表司机钱包
        DriverWallet driverWallet = new DriverWallet();
        driverWallet.setPassword(hashpw);
        driverWallet.setId(id);// 设置从表id为司机id
        walletService.save(driverWallet);
        // 从表司机配置
        DriverSetting driverSetting = new DriverSetting();
        driverSetting.setId(id);// 设置从表id为司机id
        driverSetting.setOrderDistance(driverSettingProperties.getOrderDistance());
        driverSetting.setRangeDistance(driverSettingProperties.getRangeDistance());
        settingService.save(driverSetting);
        // 从表司机统计
        DriverSummary driverSummary = new DriverSummary();
        driverSummary.setId(id);// 设置从表id为司机id
        summaryService.save(driverSummary);
    }
    /**
     * 保存driver司机对象
     * @param driver
     */
    private void saveDriver(Driver driver,String openId, String phoneCode) {
        // 通过插件实现快速生成driver带默认参数的set方法
        driver.setPhone(phoneCode);
        driver.setArchive(false);
        driver.setCreateTime(new Date());
        driver.setDeleted(false);
        driver.setVersion(0);
        driver.setOpenId(openId);
        //@TODO
        driver.setBitState(0L);
        // 设置完成后调用父类的save方法保存
        super.save(driver);
    }
}
